import forge from 'node-forge'

function generateKeyPair() {
  return new Promise((resolve, reject) => {
    try {
      resolve(forge.pki.rsa.generateKeyPair(2048))
    } catch (error) {
      reject(error)
    }
  })
}

export async function createCertificate(options = {}) {
  try {
    const keys = await generateKeyPair()
    const cert = forge.pki.createCertificate()
    
    // 基本证书信息
    cert.publicKey = keys.publicKey
    cert.serialNumber = '01' + Date.now().toString()
    cert.validity.notBefore = new Date()
    cert.validity.notAfter = new Date()
    cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1)

    // 证书属性
    const attrs = [{
      name: 'commonName',
      value: 'Electron Proxy CA'
    }, {
      name: 'countryName',
      value: 'CN'
    }, {
      name: 'organizationName',
      value: 'Electron Proxy'
    }, {
      name: 'organizationalUnitName',
      value: 'Electron Proxy Dev'
    }]

    cert.setSubject(attrs)
    cert.setIssuer(attrs)

    // 增强的扩展设置
    cert.setExtensions([{
      name: 'basicConstraints',
      cA: true,
      critical: true
    }, {
      name: 'keyUsage',
      critical: true,
      keyCertSign: true,
      digitalSignature: true,
      nonRepudiation: true,
      keyEncipherment: true,
      dataEncipherment: true
    }, {
      name: 'extKeyUsage',
      serverAuth: true,
      clientAuth: true
    }, {
      name: 'subjectKeyIdentifier'
    }, {
      name: 'subjectAltName',
      altNames: [{
        type: 2, // DNS
        value: 'localhost'
      }, {
        type: 7, // IP
        ip: '127.0.0.1'
      }]
    }])

    // 使用 SHA-256 签名证书
    cert.sign(keys.privateKey, forge.md.sha256.create())

    return {
      cert: forge.pki.certificateToPem(cert),
      key: forge.pki.privateKeyToPem(keys.privateKey)
    }
  } catch (error) {
    console.error('Error creating root certificate:', error)
    throw error
  }
}

export async function createServerCertificate(domain, caCert, caKey) {
  try {
    if (!domain || !caCert || !caKey) {
      throw new Error('Missing required parameters for server certificate creation')
    }

    console.log('Creating server certificate for domain:', domain)
    console.log('CA certificate provided:', !!caCert)
    console.log('CA key provided:', !!caKey)

    // Parse CA certificate and private key
    const caCertificate = forge.pki.certificateFromPem(caCert)
    const caPrivateKey = forge.pki.privateKeyFromPem(caKey)

    // Generate server certificate key pair
    const keys = await generateKeyPair()
    if (!keys || !keys.publicKey || !keys.privateKey) {
      throw new Error('Failed to generate key pair')
    }
    
    const cert = forge.pki.createCertificate()
    cert.publicKey = keys.publicKey
    cert.serialNumber = '02' + Date.now().toString()
    cert.validity.notBefore = new Date()
    cert.validity.notAfter = new Date()
    cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1)

    // Set server certificate attributes
    const attrs = [{
      name: 'commonName',
      value: domain
    }, {
      name: 'organizationName',
      value: 'Electron Proxy Server'
    }, {
      name: 'organizationalUnitName',
      value: 'Electron Proxy Dynamic Cert'
    }]

    cert.setSubject(attrs)
    cert.setIssuer(caCertificate.subject.attributes)

    // 设置更多的 Subject Alternative Names
    const altNames = [{
      type: 2, // DNS
      value: domain
    }]

    // 添加通配符域名
    if (!domain.startsWith('*.')) {
      altNames.push({
        type: 2,
        value: `*.${domain}`
      })
    }

    // Enhanced extension settings
    cert.setExtensions([{
      name: 'basicConstraints',
      cA: false,
      critical: true
    }, {
      name: 'keyUsage',
      critical: true,
      digitalSignature: true,
      keyEncipherment: true,
      dataEncipherment: true
    }, {
      name: 'extKeyUsage',
      serverAuth: true,
      clientAuth: true
    }, {
      name: 'subjectKeyIdentifier'
    }, {
      name: 'authorityKeyIdentifier',
      authorityCertIssuer: true,
      serialNumber: caCertificate.serialNumber
    }, {
      name: 'subjectAltName',
      altNames: altNames
    }])

    // Sign server certificate with CA private key
    cert.sign(caPrivateKey, forge.md.sha256.create())

    const certPem = forge.pki.certificateToPem(cert)
    const keyPem = forge.pki.privateKeyToPem(keys.privateKey)

    if (!certPem || !keyPem) {
      throw new Error('Failed to generate PEM format certificates')
    }

    console.log('Successfully created server certificate')
    
    return {
      cert: certPem,
      key: keyPem
    }
  } catch (error) {
    console.error('Error creating server certificate:', error)
    throw error
  }
}

// 辅助函数：验证证书
export function verifyCertificate(cert, caCert) {
  try {
    const certificate = forge.pki.certificateFromPem(cert)
    const caCertificate = forge.pki.certificateFromPem(caCert)
    return certificate.verify(caCertificate)
  } catch (error) {
    console.error('Certificate verification error:', error)
    return false
  }
}